package com.sys.service.impl;

import com.sys.dto.PlanItemRequest;
import com.sys.dto.PlanItemWithTaskDTO;
import com.sys.dto.PlanRequest;
import com.sys.entity.BizPlan;
import com.sys.entity.BizPlanItem;
import com.sys.mapper.BizPlanItemMapper;
import com.sys.mapper.BizPlanMapper;
import com.sys.service.PlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;

@Service
public class PlanServiceImpl implements PlanService {

    @Autowired
    private BizPlanMapper bizPlanMapper;

    @Autowired
    private BizPlanItemMapper bizPlanItemMapper;

    @Autowired
    private com.sys.mapper.BizTaskMapper bizTaskMapper;

    @Transactional
    @Override
    public void savePlan(PlanRequest planRequest) {
        // 创建计划对象
        BizPlan plan = new BizPlan();
        plan.setOwnerUserId(planRequest.getUserId());
        plan.setPlanName(planRequest.getPlanName());
        plan.setPlanType(planRequest.getPlanType() != null ? planRequest.getPlanType() : "weekly");
        plan.setStatus(1); // 默认有效
        plan.setDelFlag(0); // 默认未删除
        
        // 设置审计字段
        LocalDateTime now = LocalDateTime.now();
        plan.setCreateTime(now);
        plan.setUpdateTime(now);
        plan.setCreateBy(String.valueOf(planRequest.getUserId()));
        plan.setUpdateBy(String.valueOf(planRequest.getUserId()));
        
        // 转换并设置开始和结束日期
        if (planRequest.getStartDate() != null && !planRequest.getStartDate().isEmpty()) {
            plan.setStartDate(LocalDate.parse(planRequest.getStartDate()));
        }
        if (planRequest.getEndDate() != null && !planRequest.getEndDate().isEmpty()) {
            plan.setEndDate(LocalDate.parse(planRequest.getEndDate()));
        }
        
        // 如果没有提供日期范围，从 planItems 计算
        if (plan.getStartDate() == null && planRequest.getPlanItems() != null && !planRequest.getPlanItems().isEmpty()) {
            List<LocalDate> dates = new ArrayList<>();
            for (PlanItemRequest itemReq : planRequest.getPlanItems()) {
                if (itemReq.getScheduledDate() != null && !itemReq.getScheduledDate().isEmpty()) {
                    dates.add(LocalDate.parse(itemReq.getScheduledDate()));
                }
            }
            if (!dates.isEmpty()) {
                plan.setStartDate(dates.stream().min(Comparator.naturalOrder()).orElse(null));
                plan.setEndDate(dates.stream().max(Comparator.naturalOrder()).orElse(null));
            }
        }
        
        // 保存计划
        bizPlanMapper.save(plan);

        // 转换 PlanItemRequest 为 BizPlanItem 实体
        Long planId = plan.getId();
        List<BizPlanItem> planItems = new ArrayList<>();
        
        for (PlanItemRequest itemReq : planRequest.getPlanItems()) {
            BizPlanItem item = new BizPlanItem();
            item.setPlanId(planId);
            item.setTaskId(itemReq.getTaskId());
            
            // 转换日期和时间格式
            if (itemReq.getScheduledDate() != null && !itemReq.getScheduledDate().isEmpty()) {
                item.setScheduledDate(LocalDate.parse(itemReq.getScheduledDate()));
            }
            if (itemReq.getScheduledTime() != null && !itemReq.getScheduledTime().isEmpty()) {
                item.setScheduledTime(LocalTime.parse(itemReq.getScheduledTime()));
            }
            
            item.setAssignedBy(planRequest.getUserId());
            item.setAssignedTo(itemReq.getAssignedTo());
            item.setOrderIndex(itemReq.getOrderIndex());
            item.setStatus(0); // 默认待执行
            item.setDelFlag(0);
            
            // 设置审计字段
            item.setCreateTime(now);
            item.setUpdateTime(now);
            item.setCreateBy(String.valueOf(planRequest.getUserId()));
            item.setUpdateBy(String.valueOf(planRequest.getUserId()));
            
            planItems.add(item);
        }
        
        // 批量保存计划项
        if (!planItems.isEmpty()) {
            bizPlanItemMapper.saveBatch(planItems);
        }
    }

    @Override
    public List<PlanItemWithTaskDTO> getDailyTasks(Long userId) {
        return bizPlanItemMapper.findByUserIdAndDateWithTask(userId, LocalDate.now());
    }

    @Transactional
    @Override
    public void deletePlanItem(Long planItemId, Long userId) {
        // 这里可以添加权限验证，确保用户只能删除自己的计划项
        // 暂时简化处理，直接删除
        bizPlanItemMapper.deletePlanItem(planItemId, LocalDateTime.now());
    }

    @Override
    public List<BizPlan> getPlansByUserId(Long userId) {
        return bizPlanMapper.findByUserId(userId);
    }

    @Transactional
    @Override
    public void deletePlan(Long planId) {
        // 软删除计划
        BizPlan plan = new BizPlan();
        plan.setId(planId);
        plan.setDelFlag(1);
        plan.setUpdateTime(LocalDateTime.now());
        bizPlanMapper.updateById(plan);
        
        // 同时软删除该计划下的所有计划项
        bizPlanItemMapper.deleteByPlanId(planId, LocalDateTime.now());
    }

    @Override
    public BizPlan getPlanById(Long planId) {
        return bizPlanMapper.findById(planId);
    }

    @Override
    public java.util.Map<String, Object> getPlanDetailWithTasks(Long planId) {
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        
        // 获取计划基本信息
        BizPlan plan = bizPlanMapper.findById(planId);
        result.put("plan", plan);
        
        // 获取计划包含的所有任务项（带任务详情）
        if (plan != null) {
            LocalDate startDate = plan.getStartDate();
            LocalDate endDate = plan.getEndDate();
            
            if (startDate != null && endDate != null) {
                // 获取该计划时间范围内的所有计划项
                List<BizPlanItem> planItems = bizPlanItemMapper.findByUserIdAndDateRange(
                    plan.getOwnerUserId(), startDate, endDate);
                
                // 筛选出属于当前计划的项，并加载任务详情
                List<PlanItemWithTaskDTO> planItemsWithTask = new ArrayList<>();
                for (BizPlanItem item : planItems) {
                    if (item.getPlanId().equals(planId)) {
                        // 获取任务详情并组装DTO
                        PlanItemWithTaskDTO dto = new PlanItemWithTaskDTO();
                        dto.setId(item.getId());
                        dto.setPlanId(item.getPlanId());
                        dto.setTaskId(item.getTaskId());
                        dto.setScheduledDate(item.getScheduledDate());
                        dto.setScheduledTime(item.getScheduledTime());
                        dto.setStatus(item.getStatus());
                        dto.setRemark(item.getRemark());
                        
                        // 获取任务详情
                        com.sys.entity.BizTask task = bizTaskMapper.selectById(item.getTaskId());
                        dto.setTask(task);
                        
                        planItemsWithTask.add(dto);
                    }
                }
                result.put("planItems", planItemsWithTask);
            } else {
                result.put("planItems", new ArrayList<>());
            }
        } else {
            result.put("planItems", new ArrayList<>());
        }
        
        return result;
    }
}